# 四数之和，和三数之和一样的思路，不同点是 j的去重 要 j > i + 1,否则测试用例不通过，少一些元组没有选择

class Solution:
    def fourSum(self, nums, target: int):
        n = len(nums)
        rst = []

        nums.sort()
        print(nums)
        for i in range(n):
            # i 去重
            if i > 0 and nums[i] == nums[i-1]:
                continue

            for j in range(i+1, n):
                # j 去重
                if j > 1 + i and nums[j] == nums[j-1]:
                    continue

                low = j + 1
                high = n - 1
                while low < high:
                    if nums[i] + nums[j] + nums[low] + nums[high] == target:
                        rst.append([nums[i], nums[j], nums[low], nums[high]])
                        
                        x, y = nums[low], nums[high]
                        while nums[low] == x and low < high:
                            low += 1
                        while nums[high] == y and low < high:
                            high -= 1

                    elif nums[i] + nums[j] + nums[low] + nums[high] < target:
                        low += 1
                    else:
                        high -= 1

        return rst

a = [-2,-1,-1,1,1,2,2]

s = Solution()
s.fourSum(a, 0)

